home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / Ring.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  2.2 KB  |  92 lines

  1. //: C20:Ring.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Making a "ring" data structure from the STL
  7. #include <iostream>
  8. #include <list>
  9. #include <string>
  10. using namespace std;
  11.  
  12. template<class T>
  13. class Ring {
  14.   list<T> lst;
  15. public:
  16.   // Declaration necessary so the following 
  17.   // 'friend' statement sees this 'iterator' 
  18.   // instead of std::iterator:
  19.   class iterator;
  20.   friend class iterator;
  21.   class iterator : public std::iterator<
  22.     std::bidirectional_iterator_tag,T,ptrdiff_t>{
  23.     list<T>::iterator it;
  24.     list<T>* r;
  25.   public:
  26.     // "typename" necessary to resolve nesting:
  27.     iterator(list<T>& lst,
  28.       const typename list<T>::iterator& i)
  29.       : r(&lst), it(i) {}
  30.     bool operator==(const iterator& x) const {
  31.       return it == x.it;
  32.     }
  33.     bool operator!=(const iterator& x) const {
  34.       return !(*this == x);
  35.     }
  36.     list<T>::reference operator*() const {
  37.       return *it;
  38.     }
  39.     iterator& operator++() {
  40.       ++it;
  41.       if(it == r->end())
  42.         it = r->begin();
  43.       return *this;
  44.     }
  45.     iterator operator++(int) {
  46.       iterator tmp = *this;
  47.       ++*this;
  48.       return tmp;
  49.     }
  50.     iterator& operator--() {
  51.       if(it == r->begin())
  52.         it = r->end();
  53.       --it;
  54.       return *this;
  55.     }
  56.     iterator operator--(int) {
  57.       iterator tmp = *this;
  58.       --*this; 
  59.       return tmp;
  60.     }
  61.     iterator insert(const T& x){
  62.       return iterator(*r, r->insert(it, x));
  63.     }
  64.     iterator erase() {
  65.       return iterator(*r, r->erase(it));
  66.     }
  67.   };
  68.   void push_back(const T& x) {
  69.     lst.push_back(x);
  70.   }
  71.   iterator begin() {
  72.     return iterator(lst, lst.begin());
  73.   }
  74.  int size() { return lst.size(); }
  75. };
  76.  
  77. int main() {
  78.   Ring<string> rs;
  79.   rs.push_back("one");
  80.   rs.push_back("two");
  81.   rs.push_back("three");
  82.   rs.push_back("four");
  83.   rs.push_back("five");
  84.   Ring<string>::iterator it = rs.begin();
  85.   it++; it++;
  86.   it.insert("six");
  87.   it = rs.begin();
  88.   // Twice around the ring:
  89.   for(int i = 0; i < rs.size() * 2; i++)
  90.     cout << *it++ << endl;
  91. } ///:~
  92.